const DB=require('../config/zhl_DBConfig')

const fs=require('fs')
module.exports={
    //登录
    userSelect(req,resp){

        let {user,pwd}=req.query
        DB.db('select * from users where u_user=? and u_pwd=?',[user,pwd],function (err,data) {

            if (!err){
               //查询到就跳转到首页，否则就跳转到登录也
                if  (data.length>0){
                    //存储登录用户的信息到session

                    delete data[0].u_pwd
                    Object.assign(req.session,{...data[0]})
                    resp.redirect('./index.html')
                }
                else {
                    resp.redirect('./login.html')
                }
            }
            else {
                resp.send('登录失败')
                        }
        })
    },
    //注册
    registerCtrl(req,resp){
        console.log(12333333)
        let {user,pwd,name}=req.body

        let imgUploadSrc='./upload/'+req.file.filename
        console.log([user,pwd,name,imgUploadSrc])
        new Promise((resolve, reject) => {
            DB.db('insert into  users value (null,?,?,?,?)',[user,pwd,name,imgUploadSrc],function (err,data) {
                console.log(err)
                if (!err){
                   //查询到就跳转到首页，否则就跳转到登录也
                    resolve(data)
                }
                else {
                    reject({data:'错误'})
                            }

            })
        })
            .then(data=>{

                DB.db('select * from  users where u_imgSrc=?',[imgUploadSrc],function (err,data) {
                    if (!err) resp.send({code:200,data:data[0]})
                    else resp.send({code:400,msg:'查询失败请稍后重试'})
                            }
                        )

             })
    },
    //退出登录
    outLoginCtrl(req,resp){
        //销毁session返回成功
        console.log(req.session)
        req.session.destroy()
        console.log(req.session)
    resp.send({code:200})

    },
    //相册（多文件上传和展示）
    filesUploadCtrl(req,resp){

        console.log(req.session)
        let sql='insert into photo value '
        let arr=[]
        req.files.forEach((item,i)=>{
            console.log(req.files.length-1)
               let imgSrc='./upload/'+item.filename
               sql=sql+' (null,?,?)'
               arr.push(req.session.u_user)
               arr.push(imgSrc)
               if(i<req.files.length-1){
                   sql=sql+','
               }
        })
        console.log(sql)
        console.log(arr)
        new Promise((resolve, reject) => {
            DB.db(sql,arr,function (err,data) {
                if (!err){
                    //非查询类的查询返回data不能用长度判断直接判断err为空即可。
                    resolve({code:200})
                }
            })

        }).then(data=>{

              return   new Promise(resolve => {
                    let sqlSelect='select * from photo where p_user=?'
                    let arrSelect=[req.session.u_user]
                    DB.db(sqlSelect,arrSelect,function (err,data) {
                        console.log(err)
                        if (!err){
                            resolve(data)
                        }

                    })
                })

        })
            .then(data=>{
                console.log(1111111)
                resp.send(data)
            })

    },
    //相册展示
    showPhotoCtrl(req,resp){

        let {nowPage,pageI}=req.query
        let start=(nowPage-1)*pageI
        let user=req.session.u_user
         pageI=parseInt(pageI)
        console.log(user)
        let sql='select * from photo where p_user=? order by p_id desc limit ?,?'
        new Promise(resolve => {
            DB.db(sql,[user,start,pageI],function (err,data) {

                if (!err){

                    if (data.length>0){
                       resolve({photoData:data})
                    }
                    else resp.send({photoData:400,pageData:0})
                }
            })
        }).then(photoData=>{
          return new Promise(resolve => {
              let sqlP='select count(*) as maxPage from photo where p_user=? '
              DB.db(sqlP,[user],function (err,data) {
                  if (!err){
                      console.log(data)
                      let maxPage=Math.ceil(data[0].maxPage/pageI)
                      let count=data[0].maxPage
                      resolve({photoData:photoData.photoData,pageData:maxPage,dataCount:count})
                  }
              })
          })

        })
            .then(data=>{
                resp.send(data)
            })

    },
    //删除
    delImgCtrl(req,resp){
        let {delImgSrc}=req.body
        let user=req.session.u_user

   let arr=[user,delImgSrc]
        let sql='delete  from photo where p_user=? and p_imgArr=?'
           DB.db(sql,arr,function (err,data) {
                if (!err){
                    resp.send({code:200,msg:'删除成功'})
                }
                else {
                    resp.send({code:400,msg:'删除失败请重试'})
                }
           })

    },
    upCutImgCtrl(req,resp){
        let {imgCutData}=req.body
        //接受完整的文件后去掉前缀和回车+
       let imgData=imgCutData.replace(/data:image\/jpg;base64,/,'').replace('/\s/g','+')
        /*console.log(imgData)*/
        //2、把获取到的数据转成文件。
        let imgFile=Buffer.from(imgData,'base64')
        //3、创建文件名(获取图片格式)
        let fileName=new Date().getTime()+'_touxiang.jpg'
        //4 、将文件保存到upload
        fs.writeFile(`./src/upload/${fileName}`,imgFile,function (err,data) {

                if (!err){
                    //如果没有错，将数据保存到数据库。
                    let url =`./src/upload/${fileName}`
                    let user=req.session.u_user
                    let sql='insert into photo value(null,?,?) '
                    let arr=[user,url]
                    new Promise((resolve, reject) => {
                        DB.db(sql,arr,function (err,data) {
                            if (!err){
                                //非查询类的查询返回data不能用长度判断直接判断err为空即可。
                                resolve({code:200})
                            }
                        })

                    })
                        .then(data=>{

                            resp.send({code:200,msg:'上传成功'})
                        })
                /*    resp.send({code:200,msg:'上传成功'})*/

                }

        })


    }

}